/*
 * @copyright: Huang Ding
 * @Author: ding-cx
 * @Date: 2022-04-30 15:34:18
 * @LastEditors: ding-cx
 * @LastEditTime: 2022-05-26 16:51:35
 * @Description: file content
 */

import DingTalkBasePublicService from "./BasePublicService";
import { Dingtalk } from "../dingtalk";
import { ListToTree } from "@diyaner/ding";

export default class DepartmentService extends DingTalkBasePublicService {
	/** 创建部门 */
	async create(info: Dingtalk.ov.IRequestCreateDepartment) {
		const url = await this.getURL("https://oapi.dingtalk.com/topapi/v2/department/create");
		const data = info;
		const res = await this.curl<Dingtalk.ov.IResponseCreateDepartment>(url, {
			contentType: "json",
			dataType: "json",
			method: "POST",
			data,
		});
		this.ovcheckError(url, res);
		return res.data;
	}

	/** todo 暂未实现 */
	// async update(info) {
	// 	const url = await this.getURL(`https://oapi.dingtalk.com/topapi/v2/department/update`);
	// }

	/** 获取一个部门的详情 */
	async getOneDetail(dept_id: number) {
		const url = await this.getURL(`https://oapi.dingtalk.com/topapi/v2/department/get`);
		const data = {
			dept_id,
			language: "zh_CN",
		};
		const res = await this.curl<Dingtalk.ov.IResponseGetDepartmentDetail>(url, {
			contentType: "json",
			dataType: "json",
			method: "POST",
			data,
		});
		this.ovcheckError(url, res);
		return res.data;
	}

	/**
	 *  获取子部门列表
	 * - 只能获取一个父id的下属层级的部门列表的简单信息，孙子层级不能获取
	 *
	 * https://open.dingtalk.com/document/orgapp/obtain-the-department-list-v2
	 */
	async listsub(dept_id: number) {
		const url = await this.getURL(`https://oapi.dingtalk.com/topapi/v2/department/listsub`);
		const data = {
			dept_id,
			language: "zh_CN",
		};
		const res = await this.curl<Dingtalk.ov.IResponseGetDepartmentListsub>(url, {
			contentType: "json",
			dataType: "json",
			method: "POST",
			data,
		});
		this.ovcheckError(url, res);
		return res.data;
	}

	/** 通过递归调用api获取所有部门列表 */
	async getAllDepartmentList() {
		const res = await this.getOneDetail(1);
		const top = res.result;
		const allList: {
			dept_id: number;
			name: string;
			parent_id: number;
			create_dept_group: boolean;
			auto_add_user: boolean;
		}[] = [];
		allList.push({
			dept_id: 1,
			name: top.name,
			parent_id: 0, //设置为0表示没有父级部门
			create_dept_group: top.create_dept_group,
			auto_add_user: top.auto_add_user,
		});
		const recursion = async (dept_id: number) => {
			const res = await this.listsub(dept_id);
			const list = res.result;
			if (list.length === 0) return;
			allList.push(...list);
			for (const item of list) {
				await recursion(item.dept_id);
			}
		};
		await recursion(1);
		return allList;
	}

	/** 递归调用获取所有部门，并转化为tree */
	async getAllDepartmentToTree() {
		const allList = await this.getAllDepartmentList();
		const tree = ListToTree.init(allList);
		const res = tree.toTree({ id: "dept_id", parent: "parent_id", rootValue: 0, mapToLabel: "name" });
		return res;
	}
}
